package cn.weblog.api.controller;

import cn.weblog.api.domain.Catagory;
import cn.weblog.api.domain.Passage;
import cn.weblog.api.service.CatagoryService;
import cn.weblog.api.service.PassageService;
import cn.weblog.api.service.UserService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/catagory")
public class CatagoryController {

	@Autowired
	private CatagoryService catagoryService;

	@Autowired
	private PassageService passageService;

	@Autowired
	private UserService userService;

	@GetMapping("/findCatagory/{id}")	// 查询文章，显示分类名
	@ResponseBody
	public String findCatagory(@PathVariable Integer id) {
		Map<String,Object> result=new HashMap<>();
		List<Passage> passages = passageService.findCatagoryPassages(id);
		if(passages.size()==0){
			result.put("passageList",passages);
			return JSON.toJSONString(result);
		}
		result.put("catagoryName",passages.get(0).getCatagoryName());
		result.put("passageList",passages);
		return JSON.toJSONString(result);
	}


	@RequestMapping("/addCollect/{userId}")		//t 添加收藏分类 post
	@ResponseBody
	String addCollect(@RequestBody Catagory catagory,@PathVariable Integer userId){
		Catagory c=new Catagory();
		c.setCatagoryName(catagory.getCatagoryName()).setIsCollect(1).setDeleted(0).setIsTop(0).setUserId(userId);
		int i = catagoryService.addCatagory(c);
		Map<String,Object> result=new HashMap<>();
		//重新查询
	//	result.put("catagoryList",catagoryService.findCollectByUserId(userId));
		if(i==1){
			result.put("Msg","添加成功");
		}else{
			result.put("Msg","添加失败");
		}
		return JSON.toJSONString(result);
	}

	@RequestMapping("/findCollect/{userId}")	//t
	@ResponseBody
	String findCollect(@PathVariable Integer userId){
		Map<String,Object> result=new HashMap<>();
		result.put("catagoryList",catagoryService.findCollectByUserId(userId));
		return JSON.toJSONString(result);
	}

	@RequestMapping("/add/{userId}")//t 添加分类
	@ResponseBody
	String add(@RequestBody Catagory catagory,@PathVariable Integer userId){
		catagory.setUserId(userId);
		catagory.setIsTop(0);
		catagory.setDeleted(0);
		catagory.setIsCollect(0);
		int i = catagoryService.addCatagory(catagory);
	//	Map<String,Object> result=new HashMap<>();
	//	result.put("catagoryList",catagoryService.findByUserId(userId));
		String msg;
		if(i==1){
			msg="添加成功";
		}else{
			msg="添加失败";
		}
		return msg;
	}

	@RequestMapping("/findAll")//t
	@ResponseBody
	List<Catagory> findAll(){
		return catagoryService.findAll();
	}

	@RequestMapping("/findByUser/{userId}")	//t
	@ResponseBody
	String findByUser(@PathVariable Integer userId){
		Map<String,Object> result=new HashMap<>();
		result.put("catagoryList",
				catagoryService.findByUserId(userId));
		return JSON.toJSONString(result);
	}

}
